package com.aurora.source.source;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;

import com.aurora.source.BuildConfig;
import com.aurora.source.R;
import com.aurora.source.base.BaseApplication;
import com.aurora.source.source.activity.SplashActivity;
import com.aurora.source.source.bean.ProvinceBean;
import com.aurora.source.util.AssetsUtil;
import com.aurora.source.util.GreenDaoHelper;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import me.goldze.mvvmhabit.crash.CaocConfig;
import me.goldze.mvvmhabit.utils.KLog;

/**
 * Created by Lance on 2018/7/6 11:38
 */
public class SourceApplication extends BaseApplication {
    public static String versonCode = "";
    public static final String USER_ID = "userId";
    private List<Activity> activityList = new LinkedList<Activity>();
    public static RequestOptions options;
    public int clickNumber;// 点击次数
    public List<ProvinceBean> provinces;// 所有省市区数据集合
    public ArrayList<String> provinceNames;// 所有省名
    public ArrayList<ArrayList<String>> cityNames;// 所有市名
    public ArrayList<ArrayList<ArrayList<String>>> areaNames;// 所有区名

    private static SourceApplication instance;

    public static SourceApplication getInstance() {
        if (instance == null) {
            synchronized (SourceApplication.class) {
                if (instance == null) {
                    instance = new SourceApplication();
                }
            }
        }
        return instance;
    }

    @Override
    public void onCreate() {
        try {
            super.onCreate();
            instance = this;
            versonCode =getVersion();
            SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
                @NonNull
                @Override
                public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                    ClassicsHeader bezierRadarHeader= new ClassicsHeader(instance);
                    bezierRadarHeader.setAccentColorId(R.color.black_3);
                    bezierRadarHeader.setPrimaryColorId(R.color.transparence);
                    bezierRadarHeader.setTextSizeTime(12);
                    return bezierRadarHeader;
                }
            });
            /*SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
                @Override
                public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                    //指定为经典Header，默认是 贝塞尔雷达Header
                    return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Scale);
                    //    return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
                }
            });*/
            /*
            //设置全局的Footer构建器
            SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
                @Override
                public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                    //指定为经典Footer，默认是 BallPulseFooter
                    return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Scale);
                }
            });*/
            getChinaData();// 获取 中国 省市区
            options = new RequestOptions()
                    .fitCenter()
                    .placeholder(R.drawable.ic_default)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC);

          //  CrashHandler.getInstance().init(this);//异常捕获
            GreenDaoHelper.initDatabase(this);//数据库
            //是否开启打印日志
            KLog.init(BuildConfig.DEBUG);
            //初始化全局异常崩溃
            initCrash();
        } catch (Exception e) {
            e.printStackTrace();
        }

        /**
         * 二维码扫描
         */
        ZXingLibrary.initDisplayOpinion(this);
    }

    private void initCrash() {
        CaocConfig.Builder.create()
                .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
                .enabled(true) //是否启动全局异常捕获
                .showErrorDetails(true) //是否显示错误详细信息
                .showRestartButton(true) //是否显示重启按钮
                .trackActivities(true) //是否跟踪Activity
                .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
                .errorDrawable(R.mipmap.ic_launcher) //错误图标
                .restartActivity(SplashActivity.class) //重新启动后的activity
//                .errorActivity(YourCustomErrorActivity.class) //崩溃后的错误activity
//                .eventListener(new YourCustomEventListener()) //崩溃后的错误监听
                .apply();
    }

    // 获取版本号
    public String getVersion() {
        int verCode = 0;
        try {
            verCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(verCode);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    // 获取 中国 省市区
    public void getChinaData() {
        clickNumber = 0;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    provinceNames = new ArrayList<>();
                    cityNames = new ArrayList<>();
                    areaNames = new ArrayList<>();

                    initChinaJson();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }



    // 解析省市区
    private void initChinaJson() {//解析数据
        try {
            String json = AssetsUtil.getJson(this, "china.json");
            provinces = parseChinaData(json); // 用Gson 转成实体

            for (int i = 0; i < provinces.size(); i++) {
                provinceNames.add(provinces.get(i).getProvinceName());
                ArrayList<String> citys = new ArrayList<>();
                ArrayList<ArrayList<String>> areas = new ArrayList<>();//该省的所有地区列表（第三极）
                for (int j = 0; j < provinces.get(i).getCity().size(); j++) {
                    citys.add(provinces.get(i).getCity().get(j).getCityName());
                    ArrayList<String> area = new ArrayList<>();
                    for (int k = 0; k < provinces.get(i).getCity().get(j).getArea().size(); k++) {
                        area.add(provinces.get(i).getCity().get(j).getArea().get(k).getAreaName());
                    }
                    areas.add(area);
                }
                cityNames.add(citys);
                areaNames.add(areas);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 解析省市区数据
    private ArrayList<ProvinceBean> parseChinaData(String json) {
        ArrayList<ProvinceBean> arrayList = new ArrayList<>();
        try {
            JSONObject data = new JSONObject(json);
            JSONArray jsonArray = data.optJSONArray("province");
            Gson gson = new Gson();
            for (int i = 0; i < jsonArray.length(); i++) {
                ProvinceBean entity = gson.fromJson(jsonArray.optJSONObject(i).toString(), ProvinceBean.class);
                arrayList.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrayList;
    }


    //添加Activity 到容器中
    public void addActivity(Activity activity) {
        try {
            activityList.add(activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //遍历所有Activity 并finish
    public void exit() {
        try {
            for (Activity activity : activityList) {
                if (null != activity) {
                    activity.finish();
                }
            }
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
